// 观察thread id
// 和LWP有啥关系???

#include <iostream>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <functional>
#include <vector>
using namespace std;

// typedef function<void()> func_t;
using func_t = function<void()>;

const int num = 5;

class ThreadData
{
public:
    ThreadData(const string &name, const uint64_t &ctime, func_t f)
        : threadname(name), createtime(ctime), func(f)
    {
    }

public:
    string threadname;
    uint64_t createtime;
    func_t func;
};

void Print()
{
    cout << "我是线程执行的大任务的一部分" << endl;
}

// 新线程
void *ThreadRoutine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args); // 安全强转
    while (true)
    {
        cout << "new thread" << ", thread name :" << td->threadname
             << ", create time : " << td->createtime << endl;
        td->func();
        sleep(1);
    }
}

int main()
{
    vector<pthread_t> pthreads; //存放所有的线程id
    for (size_t i = 0; i < num; i++)
    {
        char threadname[64];
        
        snprintf(threadname, sizeof(threadname), "%s-%d", "thread", i);
        ThreadData *td = new ThreadData(threadname, (uint64_t)time(nullptr), Print);
        pthread_t tid;
        pthread_create(&tid, nullptr, ThreadRoutine, td);
        pthreads.push_back(tid);
        sleep(1);
    }

    cout << "thread id : ";

    for(const auto& tid : pthreads)
    {
        cout << tid << ", ";
    }
    cout << endl;

    while (true)
    {
        cout << "main thread" << endl;
        sleep(1);
    }
    return 0;
}
